//
//  CarChoiceVC.m
//  Zhiche-Carriage
//
//  Created by LeeBruce on 16/6/16.
//  Copyright © 2016年 LeeBruce. All rights reserved.
//

#import "CarChoiceVC.h"
#import "TopBackView.h"
#import "CollectionViewCell.h"
#import "Common.h"


@interface CarChoiceVC ()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>

@property (nonatomic,strong) NSMutableDictionary *dataDictionary;
@property (nonatomic,strong) NSMutableDictionary *dic;
@property (nonatomic,strong) NSMutableArray *backArray;


@property (nonatomic,strong) NSMutableArray *dataArray;
@property (nonatomic,strong) UICollectionView *collectionView;
@property (nonatomic,strong) NSIndexPath *index;

@end

@implementation CarChoiceVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.dataDictionary = [NSMutableDictionary dictionary];
    self.dic = [NSMutableDictionary dictionary];
    self.backArray = [NSMutableArray array];
    
    self.dataArray = [NSMutableArray array];
    TopBackView *topBackView= [[TopBackView alloc]initViewWithFrame:CGRectMake(0, 0, screenWidth, 64) andTitle:@"车型选择"];
    
    topBackView.rightButton.hidden = YES;
    [topBackView.leftButton addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:topBackView];
    self.view.backgroundColor = [UIColor whiteColor];
    
    
    [self initDateSource];
    
    [self initCollectionView];
}


-(void)initDateSource
{
   NSString *urlString = [NSString stringWithFormat:@"%@",truck_info];
    
    [Common requestWithUrlString:urlString contentType:application_json finished:^(id responseObj) {
        
        
        self.dataArray = [NSMutableArray arrayWithArray:responseObj[@"data"]];
        
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            // 处理耗时操作的代码块...
            [self initDataDictionary];

            //通知主线程刷新
//            dispatch_async(dispatch_get_main_queue(), ^{
//                //回调或者说是通知主线程刷新， 
//            }); 
            
        });
        
        
        if (self.dataArray.count > 0) {
            [self.collectionView reloadData];
        }
        
    } failed:^(NSString *errorMsg) {
        NSLog(@"%@",errorMsg);
    }];
    
}


-(void)initDataDictionary
{
    
    for (int i = 0; i < self.dataArray.count; i ++) {
        
        for (int j = 0; j < [self.dataArray[i][@"item"] count]; j++) {
            
             [self.dataDictionary setObject:self.dataArray[i][@"item"][j][@"code"] forKey:self.dataArray[i][@"item"][j][@"name"]];
            
        }
        
        [self.dic setObject:self.dataArray[i][@"code"] forKey:self.dataArray[i][@"name"] ];
        
        
    }
    
    self.backArray = [NSMutableArray arrayWithObjects:@"",@"",@"",@"",@"",@"",@"",@"",@"",@"",nil];
    
}


-(void)initCollectionView
{
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
    layout.itemSize = CGSizeMake(80 * kWidth, cellHeight - 10);
    
    self.collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 64, screenWidth, (30 + cellHeight) * 5) collectionViewLayout:layout];
    
    
    [self.view addSubview:self.collectionView];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    self.collectionView.backgroundColor = [UIColor whiteColor];
    
    [self.collectionView registerClass:[CollectionViewCell class] forCellWithReuseIdentifier:@"carInfoCell"];
    
    [self.collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"headerView"];
    
    
    _index = [NSIndexPath indexPathForRow:0 inSection:0];
    
    [self initBottomButton];
    
}

#pragma mark  UICollectionViewDelegate,UICollectionViewDataSource

-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{

    return  (self.dataArray.count > 0) ? self.dataArray.count :0;
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    
    return (self.dataArray > 0)? [self.dataArray[section][@"item"] count]:0;
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    static NSString *cellIden = @"carInfoCell";
    CollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellIden forIndexPath:indexPath];
    
    
    
    cell.backgroundColor = [UIColor whiteColor];
    cell.layer.borderColor = [UIColor blackColor].CGColor;
    cell.layer.borderWidth = 0.5;
    cell.layer.cornerRadius = 5;
    

    
    cell.label.text = [NSString stringWithFormat:@"%@",self.dataArray[indexPath.section][@"item"][indexPath.row][@"name"]];
//    cell.isGray = NO;
    
    return cell;
    
}
//头标题尺寸
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section
{
    return CGSizeMake(screenWidth, 30);
}
//items的偏移量
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(5, 14, 5, 0);
}

//头标题
-(UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    UICollectionReusableView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"headerView" forIndexPath:indexPath];
    
    for (UILabel *view in headerView.subviews) {
        [view removeFromSuperview];
    }
    UILabel *lable = [[UILabel alloc]initWithFrame:CGRectMake(14, 0, 100, headerView.frame.size.height)];
    lable.font = Font(15);
    
    
    lable.text = self.dataArray[indexPath.section][@"name"];
    
    
    [headerView addSubview:lable];
    headerView.backgroundColor = [UIColor grayColor];
    
    
    return headerView;
}

-(CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
    return 10;
}


-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    CollectionViewCell *oldCell = (CollectionViewCell *)[self.collectionView cellForItemAtIndexPath:_index] ;
    
    CollectionViewCell *cell = (CollectionViewCell *)[self.collectionView cellForItemAtIndexPath:indexPath] ;
    
    if (indexPath.section == _index.section && indexPath.row == indexPath.row) {
        
        cell.label.backgroundColor = [UIColor grayColor];
        
    }
    
    if (indexPath.section == _index.section && indexPath.row != _index.row) {
        oldCell.label.backgroundColor = [UIColor whiteColor];
        cell.label.backgroundColor = [UIColor grayColor];
    }
    
    if (indexPath.section != _index.section) {
        cell.label.backgroundColor = [UIColor grayColor];
        
       
        for (int i = 0; i < [self.dataArray[indexPath.section][@"item"] count]; i++) {
            CollectionViewCell *cell2 = (CollectionViewCell *)[self.collectionView cellForItemAtIndexPath:[NSIndexPath indexPathForRow:i inSection:indexPath.section]] ;
            
            cell2.label.backgroundColor = [UIColor whiteColor];
            
        }
        
        cell.label.backgroundColor = [UIColor grayColor];
    }
    
    _index = indexPath;
    
    /**
     1、TRUCK_BIN
     2、TRUCK_TRAILER
     3、TRUCK_BOX
     4、TRUCK_TYPE
     5、TRUCK_AXLE
     */

    
//        "lengthCode": "3",
//        "lengthDesc": "12-16米",
//        "widthCode": "2",
//        "widthDesc": "2.55米以下",
//        "heightCode": "2",
//        "heightDesc": "4米以下",
//        "typeCode": "2",
//        "typeDesc": "普通车",
//        "shaftTypeCode": "3",
//        "shaftTypeDesc": "五轴以下",
//        "trailerTypeCode": "2",
//        "trailerTypeDesc": "全挂",
//        "boxTypeCode": "1",
//        "boxTypeDesc": "骨架",
//        "storeNumberCode": "2",
//        "storeNumberDesc": "8-12位",
//
    
    if (indexPath.section == 0) {
        
        [self.backArray replaceObjectAtIndex:0 withObject:cell.label.text];
        [self.backArray replaceObjectAtIndex:1 withObject:self.dataDictionary[cell.label.text]];
        
    }
    
    if (indexPath.section == 1) {
        
        [self.backArray replaceObjectAtIndex:2 withObject:cell.label.text];
        [self.backArray replaceObjectAtIndex:3 withObject:self.dataDictionary[cell.label.text]];
    }
    
    if (indexPath.section == 2) {
        
        [self.backArray replaceObjectAtIndex:4 withObject:cell.label.text];
        [self.backArray replaceObjectAtIndex:5 withObject:self.dataDictionary[cell.label.text]];
    }
    
    if (indexPath.section == 3) {
        
        [self.backArray replaceObjectAtIndex:6 withObject:cell.label.text];
        [self.backArray replaceObjectAtIndex:7 withObject:self.dataDictionary[cell.label.text]];
    }
    
    if (indexPath.section == 4) {
        
        [self.backArray replaceObjectAtIndex:8 withObject:cell.label.text];
        [self.backArray replaceObjectAtIndex:9 withObject:self.dataDictionary[cell.label.text]];
    }
    

    
}


-(void)initBottomButton
{
    
    UIButton *bottomButton = [UIButton buttonWithType:UIButtonTypeCustom];
    bottomButton.frame = CGRectMake(20,10 * cellHeight + 90, screenWidth - 40, 35);
    [bottomButton setTitle:@"确认" forState:UIControlStateNormal];
    [bottomButton setTitleColor:BlackColor forState:UIControlStateNormal];
    bottomButton.titleLabel.font = Font(16);
    bottomButton.backgroundColor = YellowColor;
    bottomButton.layer.cornerRadius = 5;
    [bottomButton addTarget:self action:@selector(confirmButton) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:bottomButton];
    

}


-(void)confirmButton
{
    for (NSString *string in self.backArray) {
        if (string.length <= 0) {
            
            [self showAlertControllerWithString:@"请将信息补充完整" andInteger:0];
            
        } else {
            
            if (self.backValueString) {
                self.backValueString(self.backArray);
                
            }
    
        }
    }
    
    [self backAction];

}


-(void)backAction
{
    [self.navigationController popViewControllerAnimated:YES];
}



-(void)showAlertControllerWithString:(NSString *)string andInteger:(NSInteger)integer
{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:string message:nil preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    
    UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:nil];
    [alertController addAction:action1];
    [alertController addAction:action2];
    
    [self presentViewController:alertController animated:YES completion:nil];
    
    if (integer == 1) {
        
        //延迟执行
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            
            [alertController dismissViewControllerAnimated:YES completion:nil];
            
        });
        
    }
    
    
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
